{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "# 自定义层\n",
    "\n",
    "构造一个没有任何参数的自定义层"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.append('..')"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 6,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tensor(shape=[5], dtype=Float32, value= [-2.00000000e+00, -1.00000000e+00,  0.00000000e+00,  1.00000000e+00,  2.00000000e+00])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import mindspore\n",
    "from d2l import mindspore as d2l\n",
    "from mindspore import nn, Parameter\n",
    "\n",
    "class CenteredLayer(nn.Cell):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "\n",
    "    def construct(self, X):\n",
    "        return X - X.mean()\n",
    "\n",
    "layer = CenteredLayer()\n",
    "layer(d2l.tensor([1, 2, 3, 4, 5], mindspore.float32))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "将层作为组件合并到构建更复杂的模型中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 14,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tensor(shape=[], dtype=Float32, value= -1.16415e-10)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = nn.SequentialCell([nn.Dense(8, 128), CenteredLayer()])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "Y = net(d2l.rand((4, 8)))\n",
    "Y.mean()"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "带参数的层"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 23,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter (name=weight, shape=(5, 3), dtype=Float32, requires_grad=True)"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class MyLinear(nn.Cell):\n",
    "    def __init__(self, in_units, units):\n",
    "        super().__init__()\n",
    "        self.weight = Parameter(d2l.randn((in_units, units)))\n",
    "        self.bias = Parameter(d2l.randn((units,)))\n",
    "\n",
    "    def construct(self, X):\n",
    "        linear = d2l.matmul(X, self.weight) + self.bias\n",
    "        return d2l.relu(linear)\n",
    "\n",
    "linear = MyLinear(5, 3)\n",
    "linear.weight.value()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "使用自定义层直接执行前向传播计算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 27,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tensor(shape=[2, 3], dtype=Float32, value=\n",
       "[[ 1.32546091e+00,  3.91564280e-01,  0.00000000e+00],\n",
       " [ 0.00000000e+00,  8.59286726e-01,  2.44996011e-01]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "linear(d2l.rand((2, 5)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "-"
    }
   },
   "source": [
    "使用自定义层构建模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 31,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Tensor(shape=[2, 1], dtype=Float32, value=\n",
       "[[ 1.74028168e+01],\n",
       " [ 7.22708797e+00]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = nn.SequentialCell([MyLinear(64, 8), MyLinear(8, 1)])\n",
    "net(d2l.rand((2, 64)))"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Slideshow",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  },
  "rise": {
   "autolaunch": true,
   "enable_chalkboard": true,
   "overlay": "<div class='my-top-right'><img height=80px src='http://d2l.ai/_static/logo-with-text.png'/></div><div class='my-top-left'></div>",
   "scroll": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}